package ByteTree;

import java.io.ByteArrayOutputStream;

import Verifier.GeneralUtil;

/**
 * 
 * @author Hadar Miller
 *
 */
public class ByteTree {

	Node root;
	
	/**
	 * 
	 * @param byteArray the byte array representing the byte tree.
	 * @throws Exception when the byte array does not representing a correct byte tree.
	 */
	public ByteTree(byte [] byteArray) throws Exception 
	{
		try 
		{
			ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
			byteArrayStream.write(byteArray, 1, 4);
			/*holds the number of children or the number of bytes of the data*/
			int num = GeneralUtil.byteArrayToInt(byteArrayStream.toByteArray());
	
			byteArrayStream.reset();
			byteArrayStream.write(byteArray, 5, byteArray.length - 5);
			byte[] data = byteArrayStream.toByteArray();
	
			if (byteArray[0] == 0x01) 
			{
				root = new Leaf(num, data);
			}
			else if (byteArray[0] == 0x00)
			{
				root = new Node(num, data);
			}
		} catch (Exception e) {
			throw new Exception("a problem occured while trying to create byte tree\n" + e.getMessage());
		}
	}
	
	/**
	 * 
	 * @param node the root node of the byte tree.
	 */
	public ByteTree(Node node)
	{
		root = node;
	}
	
	/**
	 * 
	 * @return the root of the byte tree.
	 */
	public Node getRoot() 
	{
		return root;
	}
	
	/**
	 * converts the byte tree into its byte array representation.
	 * @return byte array representation of the byte tree.
	 */
	public byte[] toByteArray() throws Exception
	{
		return root.toByteArray();
	}
}

